package ar.com.android.restoapp.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;


/**
 * Static methods to detect, install, and print to a network printer with Android.
 */
public class PrintUtils
{
	// for logging
	private static final String	TAG	= PrintUtils.class.getSimpleName();

	// Send 2 Printer package name
	private static final String PACKAGE_NAME = "com.rcreations.send2printer";
	
	// intent action to trigger printing
	public static final String PRINT_ACTION = "com.rcreations.send2printer.print";

	// content provider for accessing images on local sdcard from within html content
	// sample img src shoul be something like "content://s2p_localfile/sdcard/logo.gif"
	public static final String LOCAL_SDCARD_CONTENT_PROVIDER_PREFIX = "content://s2p_localfile";

	
	/**
	 * Returns true if "Send 2 Printer" is installed. 
	 */
	public static boolean isSend2PrinterInstalled( Context context )
	{
		boolean output = false;
		PackageManager pm = context.getPackageManager();
        try { 
            PackageInfo pi = pm.getPackageInfo( PACKAGE_NAME, 0 );
            if( pi != null )
            {
            	output = true;
            }
        } catch (PackageManager.NameNotFoundException e) {}
        return output;
	}
	
	
	/**
	 * Launches the Android Market page for installing "Send 2 Printer"
	 * and calls "finish()" on the given activity.
	 */
	public static void launchMarketPageForSend2Printer( final Activity context )
	{
		AlertDialog.Builder dlgMarket = new AlertDialog.Builder(context);
				
		dlgMarket.setTitle("Install Send 2 Printer")
	        .setMessage("Before you can print to a network printer, you need to install Send 2 Printer from the Android Market.")
	        .setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick( DialogInterface dialog, int which )
				{
					// launch browser
					Uri data = Uri.parse( "http://market.android.com/search?q=pname:" + PACKAGE_NAME );
					Intent intent = new Intent( android.content.Intent.ACTION_VIEW, data );
					intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
					context.startActivity( intent );
					
					// exit
					context.finish();
				}
	        });
        
		dlgMarket.create();
		dlgMarket.show();	
	}        

    /**
     * Sends the given text for printing.
     */
    public static boolean queueTextForPrinting( Context context, String strContent )
    {
    	// send to print activity
    	Intent i = new Intent( PRINT_ACTION );
    	i.setType( "text/plain" );
    	i.putExtra( Intent.EXTRA_TEXT, strContent );
    	context.startActivity( i );
    	
    	return true;
    }
        
    
    /**
     * Save the given text to a file for printing.
     */
    public static File saveTextToTempFile( String text )
    throws IOException
    {
    	File tempFile = null;
    	    	
    	// save to temporary file
    	File dir = getTempDir();
    	if( dir != null )
    	{
			FileOutputStream fos = null;
			try
			{
				File f = File.createTempFile( "ORDER_", ".txt", dir );
				fos = new FileOutputStream( f );
				fos.write( text.getBytes() );
				tempFile = f;
			}
			catch (Exception e) {
				Log.e(TAG, e.toString());
			}
			finally
			{
				close( fos );
			}
    	}		
    	
    	return tempFile;
    }
    
    
    /**
     * Sends the given text file for printing.
     */
    public static boolean queueTextFileForPrinting( Context context, File f )
    {
    	// send to print activity
    	Uri uri = Uri.fromFile( f );
    	Intent i = new Intent( PRINT_ACTION );
    	i.setDataAndType( uri, "text/plain" );
    	i.putExtra( "deleteAfterPrint", true );
    	context.startActivity( i );
    	
    	return true;
    }    
    
	/**
	 * Return a temporary directory on the sdcard where files can be saved for printing.
	 * @return null if temporary directory could not be created.
	 */
	public static File getTempDir()
	{
		File dir = new File( Environment.getExternalStorageDirectory(), "temp" );
		if( dir.exists() == false && dir.mkdirs() == false )
		{
			Log.e( TAG, "failed to get/create temp directory" );
			return null;
		}
		return dir;
	}
		
    
    /**
     * Helper method to close given output stream ignoring any exceptions.
     */
    public static void close( OutputStream os )
    {
        if( os != null )
        {
            try
            {
                os.close();
            }
            catch( IOException e ) {}
        }
    }
}
